import React, {Component} from 'react';
import './recharge.less';
import {Form, Input, Select, Button} from 'antd';
import {reqCompanyRecharge, reqRecharge} from '../../api/index';
import {Redirect} from "react-router-dom";

const {Option} = Select;

/*
* 充值路由*/
class Demo extends Component {

    static getDerivedStateFromProps(nextProps) {
        // Should be a controlled component.
        if ('value' in nextProps) {
            return {
                ...(nextProps.value || {}),
            };
        }
        return null;
    }

    constructor(props) {
        super(props);

        const value = props.value || {};
        this.state = {
            number: value.number || 0,
            currency: value.currency || 'rmb',
        };
    }

    handleNumberChange = e => {
        const number = parseInt(e.target.value || 0, 10);
        if (Number.isNaN(number)) {
            return;
        }
        if (!('value' in this.props)) {
            this.setState({number});
        }
        this.triggerChange({number});
    };

    handleCurrencyChange = currency => {
        if (!('value' in this.props)) {
            this.setState({currency});
        }
        this.triggerChange({currency});
    };

    triggerChange = changedValue => {
        // Should provide an event to pass value to Form.
        const {onChange} = this.props;
        if (onChange) {
            onChange(Object.assign({}, this.state, changedValue));
        }
    };

    render() {
        const {size} = this.props;
        const {state} = this;
        return (
            <span>
        <Input
            type="text"
            size={size}
            value={state.number}
            onChange={this.handleNumberChange}
            style={{width: '65%', marginRight: '3%'}}
        />
        <Select
            value={state.currency}
            size={size}
            style={{width: '32%'}}
            onChange={this.handleCurrencyChange}
        >
          <Option value="rmb">RMB</Option>
        </Select>
      </span>
        );
    }
}


class Recharge extends React.Component {

    state = {
        companyInformation: [],//总的公司信息列表
    }

    //异步获取公司基本信息

    getCompanyInformation = async () => {

        //发异步ajax请求，获取数据
        const result = await reqCompanyRecharge()
        const companyInformation = result.data.results

        //更新状态
        this.setState({
            companyInformation
        })
    }

    //发异步ajax请求
    componentDidMount() {
        this.getCompanyInformation()
    }

    submit = () => {
        //进行表单验证，如果通过了，才发送请求
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                //1、搜集数据
                const {price, point} = values
                const amout = price.number
                const points = point.number
                const state = "zfcg"
                const company = 1
                const rechargeInformation = {
                    amout, points, state, company
                }
                //2、调用接口请求函数去添加/更新
                const result = await reqRecharge(rechargeInformation)
                //跳转到充值界面
                this.props.history.push('/')
                //3、根据结果提示
            } else {
                console.log('发送ajax请求失败 ');
            }
        });

    }

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    };

    checkPrice = (rule, value, callback) => {
        if (value.number > 0) {
            callback();
            return;
        }
        callback('充值金额必须大于0！');
    };
    checkPoints = (rule, value, callback) => {
        if (value.number > 0) {
            callback();
            return;
        }
        callback('积分必须大于0！');
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const {companyInformation} = this.state
        const points = companyInformation.map(item => {
            return item.points
        })
        return (
            <div className="recharge">
                <h1>公司当前剩余积分：</h1>
                <span>{points}</span>
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <Form.Item label="充值金额">
                        {getFieldDecorator('price', {
                            initialValue: {number: 0, currency: 'rmb'},
                            rules: [{validator: this.checkPrice}],
                        })(<Demo/>)}
                    </Form.Item>
                    <Form.Item label="积分">
                        {getFieldDecorator('point', {
                            initialValue: {number: 0, currency: '积分'},
                            rules: [{validator: this.checkPoints}],
                        })(<Demo/>)}
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" onClick={this.submit}>
                            充值
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }
}

const WrappedRecharge = Form.create()(Recharge);
export default WrappedRecharge;
